#! /usr/bin/env python
# -*- coding:utf-8 -*-

import socket
import os
import sys
import ctypes
import struct
from ICMPHeader import ICMP

HOST = '192.168.0.200'

def sniffing(host, win, socket_protocol=socket.IPPROTO_ICMP):
    #socket_protocol = socket.IPPROTO_ICMP
    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
    sniffer.bind((host, 0))
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    while 1:
        raw_buf = sniffer.recvfrom(65565)[0]
        ip_header = raw_buf[0:20]
        iph = struct.unpack('!BBHHHBBH4s4s', ip_header)

        version_ihl = iph[0]
        version = version_ihl >> 4
        ihl = version_ihl & 0xf
        iph_length = ihl * 4
        ttl = iph[5]
        protocol = iph[6]
        s_addr = socket.inet_ntoa(iph[8])
        d_addr = socket.inet_ntoa(iph[9])

        print 'IP ->version:' + str(version) + ', Header_length:' + str(ihl) +\
            ', TTL:' + str(ttl) + ', Protocol:' + str(protocol) + ', Source: '\
            + str(s_addr) + ', Destination:' + str(d_addr)

        buf = raw_buf[iph_length: iph_length+ctypes.sizeof(ICMP)]
        icmp_header = ICMP(buf)

        print "ICMP ->Type: %d, Code: %d" % (icmp_header.type, icmp_header.code)
        print "\n"


def main(host):
    if os.name == 'nt':
        sniffing(host, 1, socket.IPPROTO_IP)
    else:
        sniffing(host, 0, socket.IPPROTO_ICMP)


if __name__ == '__main__':
    if len(sys.argv) > 1:
        HOST = sys.argv[1]
    main(HOST)
